import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:extended_image/extended_image.dart';

import '../../common/index.dart';
import '../../config/index.dart';

import 'mine_controller.dart';

/// 我的页面
/// 个人中心和设置界面
class MinePage extends BaseGetXV<MineController> {
  MinePage({super.key});

  @override
  MineController get controller =>
      Get.put(MineController(), tag: 'MineController');
  @override
  createScaffolWidget({
    required BuildContext context,
    BoxConstraints? constraints,
  }) {
    return Scaffold(
      backgroundColor: context.theme.scaffoldBackgroundColor,
      body: createScallBody(
        context: context,
        constraints: constraints,
      ),
    );
  }

  @override
  Widget createBody({
    required BuildContext context,
    BoxConstraints? constraints,
  }) {
    return SingleChildScrollView(
      child: Column(
        children: [
          _buildHeader(context),
          _buildQuickStats(context),
          _buildMenuSection(context),
          SizedBox(height: 16.h),
          _buildSettingsSection(context),
          SizedBox(height: 20.h),
        ],
      ),
    );
  }

  /// 构建头部区域
  Widget _buildHeader(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            context.theme.primaryColor,
            context.theme.primaryColor.withOpacity(0.8),
          ],
        ),
      ),
      child: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(20.w),
          child: Column(
            children: [
              // 用户头像和基本信息
              Row(
                children: [
                  GestureDetector(
                    onTap: controller.onAvatarTap,
                    child: Obx(() => ClipRRect(
                          borderRadius: BorderRadius.circular(32.w),
                          child: ExtendedImage.network(
                            controller.userInfo?.avatar ??
                                globalConfig.defaultAvatarUrl,
                            width: 64.w,
                            height: 64.w,
                            fit: BoxFit.cover,
                            cache: true,
                            loadStateChanged: (state) {
                              if (state.extendedImageLoadState ==
                                  LoadState.failed) {
                                return Container(
                                  width: 64.w,
                                  height: 64.w,
                                  decoration: BoxDecoration(
                                    color: Colors.white.withOpacity(0.2),
                                    borderRadius: BorderRadius.circular(32.w),
                                  ),
                                  child: Icon(
                                    Icons.person,
                                    size: 32.w,
                                    color: Colors.white,
                                  ),
                                );
                              }
                              return null;
                            },
                          ),
                        )),
                  ),
                  SizedBox(width: 16.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Obx(() => Text(
                              controller.userInfo?.realName?.isNotEmpty == true
                                  ? controller.userInfo!.realName!
                                  : controller.userInfo?.username ?? '未登录',
                              style: TextStyle(
                                fontSize: 20.sp,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            )),
                        SizedBox(height: 4.h),
                        Obx(() => Text(
                              controller.userInfo?.phone?.isNotEmpty == true
                                  ? globalConfig.formatPhoneNumber(
                                      controller.userInfo!.phone!)
                                  : '请登录',
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: Colors.white.withOpacity(0.8),
                              ),
                            )),
                        SizedBox(height: 4.h),
                        Obx(() => Row(
                              children: [
                                Icon(
                                  Icons.verified_user,
                                  size: 14.w,
                                  color:
                                      controller.userInfo?.clinicAuditStatus ==
                                              1
                                          ? Colors.green
                                          : Colors.orange,
                                ),
                                SizedBox(width: 4.w),
                                Text(
                                  globalConfig.getClinicAuditStatusText(
                                      controller.userInfo?.clinicAuditStatus ??
                                          0),
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    color: Colors.white.withOpacity(0.8),
                                  ),
                                ),
                              ],
                            )),
                      ],
                    ),
                  ),
                  IconButton(
                    onPressed: controller.onSettingsTap,
                    icon: Icon(
                      Icons.settings_outlined,
                      size: 24.w,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 20.h),
              // 认证状态卡片
              Container(
                padding: EdgeInsets.all(16.w),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(
                    color: Colors.white.withOpacity(0.2),
                    width: 1,
                  ),
                ),
                child: Row(
                  children: [
                    Icon(
                      Icons.medical_services,
                      size: 20.w,
                      color: Colors.white,
                    ),
                    SizedBox(width: 8.w),
                    Expanded(
                      child: Text(
                        '医师认证',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    Obx(() => Text(
                          globalConfig.getUserAuditStatusText(
                              controller.userInfo?.userAuditStatus ?? 0),
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.white.withOpacity(0.8),
                          ),
                        )),
                    SizedBox(width: 8.w),
                    GestureDetector(
                      onTap: controller.onCertificationTap,
                      child: Icon(
                        Icons.arrow_forward_ios,
                        size: 16.w,
                        color: Colors.white.withOpacity(0.8),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建快捷统计
  Widget _buildQuickStats(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: context.theme.cardColor,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4.r,
            offset: const Offset(0, 0),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '数据概览',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: context.theme.textTheme.titleMedium?.color,
            ),
          ),
          SizedBox(height: 16.h),
          Obx(() => Row(
                children: [
                  Expanded(
                    child: _buildStatItem(
                      context,
                      title: '今日患者',
                      value: '${controller.todayPatients}',
                      color: Colors.blue,
                      onTap: controller.onTodayPatientsTap,
                    ),
                  ),
                  Expanded(
                    child: _buildStatItem(
                      context,
                      title: '本月收入',
                      value: globalConfig.formatPrice(controller.monthlyIncome),
                      color: Colors.green,
                      onTap: controller.onMonthlyIncomeTap,
                    ),
                  ),
                  Expanded(
                    child: _buildStatItem(
                      context,
                      title: '待处理',
                      value: '${controller.pendingCount}',
                      color: Colors.orange,
                      onTap: controller.onPendingTasksTap,
                    ),
                  ),
                  Expanded(
                    child: _buildStatItem(
                      context,
                      title: '总评分',
                      value: '${controller.totalRating}',
                      color: Colors.red,
                      onTap: controller.onTotalRatingTap,
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(
    BuildContext context, {
    required String title,
    required String value,
    required Color color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Text(
            value,
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SizedBox(height: 4.h),
          Text(
            title,
            style: TextStyle(
              fontSize: 12.sp,
              color: context.theme.textTheme.bodySmall?.color,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建菜单区域
  Widget _buildMenuSection(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          _buildMenuGroup(
            context,
            title: '业务管理',
            items: [
              MenuItemModel(
                icon: Icons.people_outline,
                title: '患者管理',
                subtitle: '查看和管理患者信息',
                onTap: controller.onPatientManagementTap,
              ),
              MenuItemModel(
                icon: Icons.receipt_long_outlined,
                title: '处方管理',
                subtitle: '查看和管理处方记录',
                onTap: controller.onPrescriptionManagementTap,
              ),
              MenuItemModel(
                icon: Icons.shopping_cart_outlined,
                title: '采购订单',
                subtitle: '查看采购历史和订单状态',
                onTap: controller.onPurchaseOrderTap,
              ),
              MenuItemModel(
                icon: Icons.analytics_outlined,
                title: '数据统计',
                subtitle: '查看详细的业务数据分析',
                onTap: controller.onDataStatisticsTap,
              ),
            ],
          ),
          SizedBox(height: 16.h),
          _buildMenuGroup(
            context,
            title: '个人中心',
            items: [
              MenuItemModel(
                icon: Icons.person_outline,
                title: '个人信息',
                subtitle: '编辑个人资料和认证信息',
                onTap: controller.onPersonalInfoTap,
              ),
              MenuItemModel(
                icon: Icons.security_outlined,
                title: '账号安全',
                subtitle: '修改密码和安全设置',
                onTap: controller.onAccountSecurityTap,
              ),
              MenuItemModel(
                icon: Icons.notifications_outlined,
                title: '消息通知',
                subtitle: '管理通知和提醒设置',
                onTap: controller.onMessageNotificationTap,
              ),
              MenuItemModel(
                icon: Icons.help_outline,
                title: '帮助中心',
                subtitle: '常见问题和使用指南',
                onTap: controller.onHelpCenterTap,
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建菜单组
  Widget _buildMenuGroup(
    BuildContext context, {
    required String title,
    required List<MenuItemModel> items,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: context.theme.cardColor,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4.r,
            offset: const Offset(0, 0),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.all(16.w),
            child: Text(
              title,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: context.theme.textTheme.titleMedium?.color,
              ),
            ),
          ),
          ...items.asMap().entries.map((entry) {
            final index = entry.key;
            final item = entry.value;
            return Column(
              children: [
                if (index > 0)
                  Divider(
                    height: 0.5,
                    color: context.theme.dividerColor.withOpacity(0.05),
                    indent: 16,
                    endIndent: 16,
                  ),
                _buildMenuItem(context, item),
              ],
            );
          }),
        ],
      ),
    );
  }

  /// 构建菜单项
  Widget _buildMenuItem(BuildContext context, MenuItemModel item) {
    return ListTile(
      leading: Icon(
        item.icon,
        size: 24.w,
        color: context.theme.primaryColor,
      ),
      title: Text(
        item.title,
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w500,
          color: context.theme.textTheme.titleMedium?.color,
        ),
      ),
      subtitle: item.subtitle != null
          ? Text(
              item.subtitle!,
              style: TextStyle(
                fontSize: 12.sp,
                color: context.theme.textTheme.bodySmall?.color,
              ),
            )
          : null,
      trailing: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (item.badge != null)
            Container(
              padding: EdgeInsets.symmetric(
                horizontal: 6.w,
                vertical: 2.h,
              ),
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(10.r),
              ),
              child: Text(
                item.badge!,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          if (item.badge != null) SizedBox(width: 8.w),
          Icon(
            Icons.arrow_forward_ios,
            size: 16.w,
            color: context.theme.textTheme.bodySmall?.color,
          ),
        ],
      ),
      onTap: item.onTap,
      contentPadding: EdgeInsets.symmetric(
        horizontal: 16.w,
        vertical: 4.h,
      ),
    );
  }

  /// 构建设置区域
  Widget _buildSettingsSection(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          _buildMenuGroup(
            context,
            title: '应用设置',
            items: [
              MenuItemModel(
                icon: Icons.palette_outlined,
                title: '主题设置',
                subtitle: '切换深色/浅色主题',
                onTap: controller.onThemeSettingsTap,
              ),
              MenuItemModel(
                icon: Icons.language_outlined,
                title: '语言设置',
                subtitle: '选择应用语言',
                onTap: controller.onLanguageSettingsTap,
              ),
              MenuItemModel(
                icon: Icons.info_outline,
                title: '关于我们',
                subtitle: '版本信息和服务条款',
                onTap: controller.onAboutTap,
              ),
            ],
          ),
          SizedBox(height: 16.h),
          // 退出登录按钮
          if (globalConfig.isLoggedIn)
            Container(
              width: double.infinity,
              margin: EdgeInsets.symmetric(horizontal: 16.w),
              child: ElevatedButton(
                onPressed: controller.onLogoutTap,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red.withOpacity(0.1),
                  foregroundColor: Colors.red,
                  elevation: 0,
                  padding: EdgeInsets.symmetric(vertical: 12.h),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.r),
                    side: BorderSide(
                      color: Colors.red.withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                ),
                child: Text(
                  StringConfig.logout,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

/// 菜单项模型
class MenuItemModel {
  final IconData icon;
  final String title;
  final String? subtitle;
  final String? badge;
  final VoidCallback onTap;

  MenuItemModel({
    required this.icon,
    required this.title,
    this.subtitle,
    this.badge,
    required this.onTap,
  });
}
